package com.baidu.camera.ui;

import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;

import com.baidu.camera.R;
import com.baidu.camera.utils.FileUtils;
import com.baidu.camera.utils.ToastUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@EActivity(R.layout.activity_camera)
public class TextureCameraActivity extends AppCompatActivity implements TextureView.SurfaceTextureListener, View.OnTouchListener {
    Camera camera;
    int zoom;
    Camera.ShutterCallback shutterCallback;
    Camera.PictureCallback pictureCallback;
    int d = 90;
    @ViewById
    Button submit;
    @ViewById
    Button next;
    @ViewById
    TextureView surface;
    @ViewById
    Button degree;
    @ViewById
    Button add;
    @ViewById
    Button decrease;
    private BufferedOutputStream bos;
    private Camera.AutoFocusCallback autoFocusCallback;

    @AfterViews
    void initCamera() {
//        initOptions();
        initSimpleCamera();
    }

    private void initSimpleCamera() {
        camera = Camera.open();
        camera.setDisplayOrientation(d);
        surface.setSurfaceTextureListener(this);
        surface.setOnTouchListener(this);
        pictureCallback = new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                storeImage(data);
            }
        };
        autoFocusCallback = new Camera.AutoFocusCallback() {
            @Override
            public void onAutoFocus(boolean success, Camera camera) {
                if (success) {
                    ToastUtils.simpleToast(getApplicationContext(), "focus success");
                } else {
                    ToastUtils.simpleToast(getApplicationContext(), "focus fail");
                }
            }
        };

        //set camera options
        Camera.Parameters parameters = camera.getParameters();
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
        camera.setParameters(parameters);
    }

    private void initOptions() {
        camera = Camera.open();
        Camera.Parameters parameters = camera.getParameters();
        parameters.setJpegQuality(50);
        camera.setParameters(parameters);
        camera.setDisplayOrientation(180);
        try {
//            camera.setPreviewDisplay(surface.getHolder());
            camera.startPreview();
        } catch (Exception e) {
            e.printStackTrace();
        }

        shutterCallback = new Camera.ShutterCallback() {
            @Override
            public void onShutter() {

            }
        };
        pictureCallback = new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                storeImage(data);
            }
        };


    }

    private void storeImage(byte[] data) {
        File f = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            f = FileUtils.createImageFile(Environment.getExternalStorageDirectory() + "/img");
        }
        if (f.exists()) {
            try {
                String src = f.getAbsolutePath();
                bos = new BufferedOutputStream(new FileOutputStream(f));
                bos.write(data, 0, data.length);
                bos.flush();
                ToastUtils.simpleToast(this, "store successfully");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Click({R.id.submit, R.id.next, R.id.degree, R.id.add, R.id.decrease})
    void click(View v) {
        switch (v.getId()) {
            case R.id.submit:
                camera.takePicture(null, null, pictureCallback);
                break;
            case R.id.next:
                camera.startPreview();
                break;
            case R.id.degree:
                resetDegree();
                camera.startPreview();
                break;
            case R.id.add:
                resetZoom(++zoom);
                camera.startSmoothZoom(++zoom);
                camera.startPreview();
                break;
            case R.id.decrease:
                camera.startSmoothZoom(--zoom);
                camera.startPreview();
                break;
        }
    }

    //set zoom
    private void resetZoom(int i) {
        Camera.Parameters parameters = camera.getParameters();
        if (parameters.isZoomSupported()) {
            parameters.setZoom(i);
            camera.setParameters(parameters);
        }
    }

    //set rotating degree
    private void resetDegree() {
        d += 90;
        if (d == 360) {
            d = 0;
        }
        camera.setDisplayOrientation(d);
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {

        try {
            camera.setPreviewTexture(surface);//binding surface
            camera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        camera.stopPreview();
        camera.release();
        return true;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        camera.autoFocus(autoFocusCallback);
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        camera.autoFocus(autoFocusCallback);
        return false;
    }
}
